package be.bonamis.umpire.ui.server.utils;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import be.bonamis.umpire.business.UmpireService;

public class ReportServlet extends HttpServlet {
	private static final long serialVersionUID = 932649922269677809L;
	private static final Logger LOG = LoggerFactory.getLogger(ReportServlet.class);

	@Autowired
	UmpireService service;
	
	@Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        final WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        context.getAutowireCapableBeanFactory().autowireBean(this);
    }	

	protected void doGet(HttpServletRequest request, HttpServletResponse response){		
		String leagueDayId = request.getParameter("leagueDayId");
		byte[] xlsArrayBytes = service
				.generateUmpireByLeaguedayXlsFile(Long.parseLong(leagueDayId));

		response.setHeader("Pragma", "");
		response.setHeader("Cache-Control", "");
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment; filename=MyExcel.xls");

		ServletOutputStream out;
		try {
			out = response.getOutputStream();
			out.write(xlsArrayBytes);
		} catch (IOException e) {
			LOG.error("XLS reporting Engine was not able to generate the list of Umpire", e);			
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response) Do nothing
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}
